import { getMenuUser } from "@/api/system/menu";
import { useAuthStore } from "@/stores/auth";
import type { RouteComponent, RouteRecordRaw } from "vue-router";
import router from "@/router";
import { dynamicRoutes, defaultRoutes } from "@/router";
import { useViewRoutesStore } from '@/stores/viewRoutes'



// 获取 src/views 目录下的 .vue 文件，排除其 components 目录下的子组件文件
const modules: Record<string, RouteComponent> =
    import.meta.glob(['../views/**/*.vue', '!../views/components/**'])

// 相对路径路由模块：将key本地路由组件路 src/views 或 ../views 都替换为 ''
const viewsModules: Record<string, RouteComponent> = Object.keys(modules).reduce((prevObj, currKey) => Object.assign(prevObj, { [currKey.replace(/(..\/views\/|\.vue)/g, '')]: modules[currKey] }), {})


// 根据后端返回路由数据，进行动态路由控制
export async function initBackEndRoutes() {
    // 判断是否登录
    const authStore = useAuthStore()
    if (!authStore.accessToken) return false;

    // 请求接口获取用户拥有的权限菜单
    const { data } = await getMenuUser()
    const { userInfo, menuList, buttonList } = data

    // 没有任何菜单权限，返回 false
    if (!userInfo || !menuList || menuList.length <= 0) return false

    authStore.setUserInfo(userInfo)
    // authStore.setMenuList(menuList)
    authStore.setButtonList(buttonList)

    // 路由对象中 component 属性的字符串值，从 viewsModules 中查找对应的动态导入路由组件方法
    dynamicRoutes[0].children = dynamicImportComponent(menuList)

    // 添加动态路由
    addRouteHandle()

    // 存储动态路由到 pinia store
    setDynamicRoutes()

    // 存储缓存路由名到 pinia store
    setCacheRouteNames()
}

// 后端路由表中 component 转换为动态导入路由组件
export function dynamicImportComponent(dynamicRoutes: RouteRecordRaw[]) {
    if (!dynamicRoutes || dynamicRoutes.length <= 0) return
    return dynamicRoutes.map(route => {
        // 存在component值，则查找对应动态导入组件方法
        const { component } = route
        // 去除 component 中的 .vue 后缀
        const componentStr = `${component}`.replace(/(..\/views\/|\.vue)/g, '')
        if (component) route.component = viewsModules[`${componentStr}`] || viewsModules[`/${componentStr}`]
        route.children && dynamicImportComponent(route.children)
        return route
    })
}

// 添加动态路由
export function addRouteHandle() {
    const layoutRouteChildren = [...dynamicRoutes[0].children || [], ...defaultRoutes]
    dynamicRoutes[0].children = layoutRouteChildren
    dynamicRoutes.forEach(route => {
        router.addRoute(route)
    })
}

// 将动态路由保存到pinia中
function setDynamicRoutes() {
    const authStore = useAuthStore()
    authStore.setMenuList(dynamicRoutes[0].children || [])
}

// 获取需要缓存的路由名称存到pinia中
export function setCacheRouteNames() {
    const cacheRouteNames: string[] = []
    const _getNames = (route: RouteRecordRaw) => {
        // 获取缓存路由的name值
        if (route.meta?.cache && route.name) {
            cacheRouteNames.push(route.name as string)
        }
        // 有子路由，则递归获取name值
        if (route.children && route.children.length > 0) {
            route.children.forEach(item => {
                _getNames(item)
            })
        }
    }
    _getNames(dynamicRoutes[0])
    // 保存到pinia
    const viewRoutesStore = useViewRoutesStore()
    viewRoutesStore.setCacheRouteNames(cacheRouteNames)
}
